package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.result.Result;
import com.itheima.service.UserService;
import com.itheima.vo.UserInfoVo;
import com.itheima.vo.VisitorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * 用户控制器
 *
 * @author itheima
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户首页信息
     *
     * @param userId 用户编号
     * @return Result
     */
    @GetMapping("user/{userId}/info")
    public Result getUserInfo(@PathVariable String userId) {
        if (Objects.isNull(userId)) {
            return new Result(400, "用户编号不能为空", null);
        }

        UserInfoVo userInfo = userService.getUserInfo(userId);
        return new Result(200, "", userInfo);
    }

    /**
     * 获取用户详细信息
     *
     * @param userId 用户编号
     * @return Result
     */
    @GetMapping("user/{userId}/detail")
    public Result getUserDetail(@PathVariable String userId) {
        if (Objects.isNull(userId)) {
            return new Result(400, "用户编号不能为空", null);
        }

        return new Result(200, "", userService.getUserDetail(userId));
    }

    /**
     * 修改用户信息
     *
     * @return Result
     */
    @PutMapping("user")
    public Result modify(@Valid @RequestBody User user, Errors errors) {
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return new Result(400, fieldError.getDefaultMessage(), null);
        }

        return new Result(userService.updateById(user) ? 200 : 500, "", null);
    }

    /**
     * 获得访问者列表
     *
     * @return Result
     */
    @GetMapping("user/{userId}/visitor/list")
    public Result getVisitorList(@PathVariable String userId) {
        VisitorVo visitorList = userService.getVisitorList(userId);
        return new Result(200, "", visitorList);
    }
}
